package com.electron.power.aio.common;

import com.electron.power.aio.common.exception.BizException;

public class DataExchangeUtils {
	public static final int FF=0xff; 
	
	
	public static String converByteArray2String(byte[] sourceData) {
		StringBuilder resultBuilder = new StringBuilder();
		for (int i = 0; i < sourceData.length; i++) {
			Byte t = sourceData[i];
			String data = t.toString();
			if (data.length() == 1) {
				data = "0" + data;
			}
			resultBuilder.append(data);
		}
		return resultBuilder.toString();

		// final StringBuilder result = new StringBuilder();
		//
		// Stream<byte[]> dataStream = Stream.of(sourceData);
		//
		// dataStream.forEach(byteData -> {
		// result.append(byteData.toString());
		// });
		//
		// return result.toString();
	}

	public static int getUnsignedByte(byte data) { // 将data字节型数据转换为0~255 (0xFF 即BYTE)。
		return data & 0x0FF;
	}

	public static int getUnsignedByte(short data) { // 将data字节型数据转换为0~65535 (0xFFFF 即 WORD)。
		return data & 0x0FFFF;
	}

	public static long getUnsignedIntt(int data) { // 将int数据转换为0~4294967295 (0xFFFFFFFF即DWORD)。
		return data & 0x0FFFFFFFFl;
	}

	public static byte[] int2byte(int res) {
		byte[] targets = new byte[4];
		targets[0] = (byte) (res & 0xff);// 最低位
		targets[1] = (byte) ((res >> 8) & 0xff);// 次低位
		targets[2] = (byte) ((res >> 16) & 0xff);// 次高位
		targets[3] = (byte) (res >>> 24);// 最高位,无符号右移。
		return targets;
	}

//	public static int byte2int(byte[] res) {
//		// 一个byte数据左移24位变成0x??000000，再右移8位变成0x00??0000
//		int targets = (res[0] & 0xff) | ((res[1] << 8) & 0xff00) // | 表示安位或
//				| ((res[2] << 24) >>> 8) | (res[3] << 24);
//		return targets;
//	}
	
	/**
	 * 将byte转换成int,byte数组最大长度为3.否则转换成long.
	 * @param byteArray
	 * @return
	 */
	public static int byte2int(byte[] byteArray) {
		if(byteArray.length>3) {
			throw new BizException("byte数组长度超过3");
		}
		int result = 0;
		int arrayLenth = byteArray.length;
		for(int i = 0;i<arrayLenth;i++) {
			byte byteBit = byteArray[i];
			int leftMoveBit = (byteBit&FF)<<(arrayLenth-i-1)*8;
			result = result|leftMoveBit;
		}
		return result;
	}
	
	public static long byte2long(byte[] byteArray) {
		if(byteArray.length<4) {
			throw new BizException("byte数组长度小于4");
		}
		long result = 0;
		int arrayLenth = byteArray.length;
		for(int i = 0;i<arrayLenth-1;i++) {
			byte byteBit = byteArray[i];
			long leftMoveBit = (byteBit&FF)<<(arrayLenth-i-1)*8;
			result = result|leftMoveBit;
		}
		return result;
	}

	public static void main(String[] args) {
		byte[] b = new byte[] {-1};
		System.out.println(-2&0xff);
	}
}
